from PIL import Image
import os

class grabImage(object):
    def __init__(self,initialPoint,width,height,stepX,stepY,imagefolder):
        self.initialPoint = initialPoint
        self.imgWidth = width
        self.imgHeight = height
        self.imagefolder = imagefolder

        folderpaths = os.listdir(imagefolder)
        for path in folderpaths:
            if path.split('.')[-1] in ['png','jpg','bmp','tif','ico','jpeg']:
                imagePath = os.path.join(imagefolder,path)
                print('============='+imagePath+'===================')
                self.jieImage(imagePath, stepX, stepY)

    def jieImage(self,imagePath,stepX,stepY):

        imgSavePath =os.path.dirname(self.imagefolder) + '/jieImage'

        if not os.path.exists(imgSavePath):
            os.makedirs(imgSavePath)

        image = Image.open(imagePath)
        imageW = image.size[0]
        imageH = image.size[1]

        numX = (imageW-self.initialPoint[0])//stepX + 1
        numY = (imageH-self.initialPoint[1])//stepY + 1
        self.x = self.initialPoint[0]
        self.y = self.initialPoint[1]
        n = 0
        for i in range(numX):
            for j in range(numY):

                if self.x + self.imgWidth < imageW:
                    if self.y + self.imgHeight < imageH:
                        img = image.crop((self.x, self.y, self.x+self.imgWidth, self.y+self.imgHeight))
                        self.y += stepY
                    else:
                        img = image.crop((self.x, imageH-self.imgHeight, self.x+self.imgWidth, imageH-self.imgHeight+self.imgHeight))
                        self.x += stepX
                        self.y = self.initialPoint[1]
                else:
                    if self.y + self.imgHeight < imageH:
                        img = image.crop((imageW - self.imgWidth, self.y, imageW - self.imgWidth+self.imgWidth, self.y+self.imgHeight))
                        self.x = self.initialPoint[0]
                        self.y += stepY
                    else:
                        img = image.crop((imageW - self.imgWidth, imageH - self.imgHeight, imageW - self.imgWidth+self.imgWidth,
                                             imageH - self.imgHeight+self.imgHeight))
                n+=1

                baseName = os.path.basename(imagePath).split('.')
                img.save(imgSavePath+'/'+baseName[0] + '_' + str(n) + '.' + baseName[1])

# grabImage((0,0),200,200,100,100,'C:/Users/dell/Desktop/proxima interface screenshot')